package com.example.tnuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.tnuser.mapper.UserMapper;
import com.example.tnuser.service.UserService;
import com.yc.pojo.User;
import com.yc.util.Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;

    /**
     * 根据openid查询是否注册,注册则返回对象信息
     *
     * @param openID
     * @return
     */
    public User selectUser(String openID) {
        System.out.println("openID = " + openID);
        User user = userService.lambdaQuery()
                .eq(User::getOpenID, openID)
                .one();
        return user;
    }

    /**
     * 查询该手机号是否被绑定
     *
     * @param phone
     * @return
     */
    public boolean havaPhone(String phone) {
        User user = userService.lambdaQuery()
                .select(User::getPhone)
                .eq(User::getPhone, phone)
                .one();
        if (user == null) {
            return false;
        }
        return true;
    }

    /**
     * 填写的手机号是否绑定openid
     *
     * @param phone
     * @return
     */
    public boolean havaCode(String phone) {
        User user = userService.lambdaQuery()
                .select(User::getOpenID)
                .eq(User::getPhone, phone)
                .one();
        System.out.println(user);
        if (! Utils.isEmpty(user)) {
            return false;
        }
        return true;
    }


    /**
     * 号码和openid 都没有被使用，直接新增注册
     *
     * @param phone
     * @param openid
     */
    public void insertUser(String phone, String openid ,String img) {
        User newuser = new User();
        newuser.setPhone(phone);
        newuser.setOpenID(openid);
        newuser.setUserName(phone);
        newuser.setImage(img);
        userService.save(newuser);
    }


    /**
     * openid没被绑定但手机号存在，则更新openid到手机号这个图记录
     * @param phone
     * @param openid
     */
    public void updateUser(String phone, String openid,String img) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(User::getPhone, phone)
                .set(User::getOpenID, openid)
                .set(User::getImage, img);


        userMapper.update(null,updateWrapper);
    }
}
